package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo<ApUserRealname> findPage(ApUserRealnamePageRequestDto dto) {
        //分页条件设置
        IPage<ApUserRealname> pageList = new Page<>(dto.getPage(),dto.getSize());
        //分页条件
        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null!=dto.getStatus(),ApUserRealname::getStatus,dto.getStatus());
        page(pageList,lqw);
        return PageResultVo.pageResult(dto.getPage(),dto.getSize(),pageList.getTotal(),pageList.getRecords());
    }

    /**
     * 申请驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //获取参数
        Integer keyId = (Integer) paramMap.get("id");
        String reason = (String) paramMap.get("msg");
        //构建更新对象
        ApUserRealname pojo = new ApUserRealname();
        pojo.setReason(reason);
        pojo.setId(keyId);
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        pojo.setUpdatedTime(LocalDateTime.now());
        updateById(pojo);
    }


    /**
     * 申诉通过
     *
     * @param paramMap
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void authPass(Map<String, Object> paramMap) {
        //参数检验
        Integer id = (Integer) paramMap.get("id");
        log.debug("实名认证：id{}",id);
        if (null == id){
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }

        //更新用户信息，认证通过 自媒体人
        ApUserRealname apUserRealname = getById(id);
        if (null == apUserRealname){
            throw new LeadNewsException(HttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer appUserId = apUserRealname.getUserId();

        ApUser appUserInfo = apUserMapper.selectById(appUserId);

        // 远程调用  创建自媒体账号
        Integer wmUserId = addWmUser(appUserId,appUserInfo);
        log.debug("实名认证 添加自媒体账号成功：id={},appUserId={},wmUserId={}",id,appUserId,wmUserId);
        // 远程调用 创建作者账号
        addApAuthor(wmUserId,appUserInfo);
        log.debug("实名认证  添加作者账号成功：id={},appUserId={},wmUserId={}",id,appUserId,wmUserId);

        //更新实名认证状态
        ApUserRealname pojo = new ApUserRealname();
        pojo.setId(id);
        pojo.setUpdatedTime(LocalDateTime.now());
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        updateById(pojo);
        log.debug("实名认证更新认证状态id{}",id);


        //更新用户信息
        ApUser apUser = new ApUser();
        apUser.setId(appUserId);
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        //从普通用户升级自媒体人
        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        apUserMapper.updateById(apUser);
        log.debug("实名认证 从普通用户升级为自媒体人：id{},appUserId{}",id,appUserId);

    }


    /**
     * 添加作者信息
     * @param wmUserId
     * @param appUserInfo
     */
    private void addApAuthor(Integer wmUserId, ApUser appUserInfo) {
        //查询作者信息是否存在
        ResultVo<ApAuthor> getResult= apAuthorFeign.getByApUserIdWmUserId(appUserInfo.getId(), wmUserId);
        if (!getResult.isSuccess()){
            throw new LeadNewsException("查询作者信息失败");
        }
        //获取返回数据
        ApAuthor apAuthor = getResult.getData();
        //不存在则添加
        if (null == apAuthor){
            apAuthor  = new ApAuthor();
            apAuthor.setName(appUserInfo.getName());
            apAuthor.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            apAuthor.setUserId(appUserInfo.getId());
            apAuthor.setWmUserId(wmUserId);
            apAuthor.setCreatedTime(LocalDateTime.now());
            //远程调用添加
            ResultVo addResult = apAuthorFeign.add(apAuthor);
            if (addResult.isSuccess()){
                throw new LeadNewsException("调用文章微服务 添加作者信息失败");
            }
        }
    }


    /**
     * 添加自媒体账号
     * @param appUserId
     * @param appUserInfo
     * @return
     */
    private Integer addWmUser(Integer appUserId, ApUser appUserInfo) {
        ResultVo<WmUser> wmUserResult = wmUserFeign.getByAppUserId(appUserId);
        if (!wmUserResult.isSuccess()) {
            throw new LeadNewsException("调用自媒体微服务失败");
        }
        WmUser wmUser = wmUserResult.getData();
        // 4.2 如果不存在添加
        if(null == wmUser){
            //4.3 创建自媒体账号
            wmUser = new WmUser();
            BeanUtils.copyProperties(appUserInfo, wmUser);
            wmUser.setId(null);
            wmUser.setApUserId(appUserId);
            wmUser.setNickname(appUserInfo.getName());
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setScore(0);
            wmUser.setCreatedTime(LocalDateTime.now());
            ResultVo<WmUser> insertResult = wmUserFeign.add(wmUser);
            if(!insertResult.isSuccess()){
                // 添加自媒体失败了
                throw new LeadNewsException("调用自媒体微服务添加账号失败");
            }
            // 为什么???
            wmUser = insertResult.getData();
        }
        return wmUser.getId();
    }


}
